package com.ctg.itrdc.sysmgr.portal.control;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ctg.itrdc.sysmgr.portal.api.dto.FuncMenuDTO;
import com.ctg.itrdc.sysmgr.portal.api.dto.PlatInfoDTO;
import com.ctg.itrdc.sysmgr.portal.api.service.IFuncMenuService;
import com.ctg.itrdc.sysmgr.portal.api.service.IPlatInfoService;
import com.ctg.itrdc.sysmgr.portal.common.entity.CommonResult;
import com.ctg.itrdc.sysmgr.portal.utils.DTOHelper;

@Controller
@RequestMapping("/plat_info")
public class PlatInfoController extends SysmgrCURDController<Long, PlatInfoDTO> {
	
	@Resource
	private IPlatInfoService platInfoService;
	@Resource
	private IFuncMenuService funcMenuService;
	
	@RequestMapping("/create")
	@ResponseBody
	public CommonResult insert(PlatInfoDTO dto) throws Exception {
		String nbrStr = dto.getPlatSysNbr();
		if(nbrStr != null) {
			PlatInfoDTO existedInfo = platInfoService.selectByPlatSysNbr(nbrStr);
			if(existedInfo != null) {
				return new CommonResult(HttpStatus.NOT_ACCEPTABLE.toString(), "平台编码已存在");
			}
		}
		Long i = platInfoService.insert(dto);
		return new CommonResult(HttpStatus.OK.toString(), "新增数据成功",i);
	}
	
    @RequestMapping("/edit")
	@ResponseBody
	public CommonResult updateByPrimaryKey(PlatInfoDTO dto) throws Exception {
    	if(dto.getPlatSysNbr() != null && dto.getId() != null) {
    		PlatInfoDTO existedInfo = platInfoService.selectByPlatSysNbr(dto.getPlatSysNbr());
			if(existedInfo != null && existedInfo.getId() != dto.getId()) {
				return new CommonResult(HttpStatus.NOT_ACCEPTABLE.toString(), "平台编码已存在");
			}
			// 修改的code之前不存在，或者code改变，才去修改菜单中的system_code
			if(existedInfo == null || !dto.getPlatSysNbr().equals(existedInfo.getPlatSysNbr())) {
		    	FuncMenuDTO menuDTO = new FuncMenuDTO();
		    	PlatInfoDTO platInfoDTO = platInfoService.selectByPrimaryKey(dto.getId());
		    	menuDTO.setSysCode(platInfoDTO.getPlatSysNbr());
		    	List<FuncMenuDTO> menuList = funcMenuService.selectByExample(menuDTO);
		    	for(FuncMenuDTO mdto : menuList) {
		    		mdto.setSysCode(dto.getPlatSysNbr());
		    	}
		    	funcMenuService.batchUpdateByPrimaryKey(menuList);
    		}
    	}
		DTOHelper.updateDTO(dto);
		int i = platInfoService.updateByPrimaryKey(dto);
		return new CommonResult(HttpStatus.OK.toString(), "更新数据成功",i);
	}
         
}
